package com.wenzhoujie.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lingou.www.R;

public class SDMoreView extends LinearLayout implements OnClickListener
{

	private LinearLayout mLlContent = null;
	private TextView mTvMore = null;

	private SDMoreViewBaseAdapter mAdapter = null;

	public SDMoreViewBaseAdapter getAdapter()
	{
		return mAdapter;
	}

	public void setAdapter(SDMoreViewBaseAdapter adapter)
	{
		this.mAdapter = adapter;
		initViewState(false);
	}

	public SDMoreView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		init();
	}

	public SDMoreView(Context context)
	{
		super(context);
		init();
	}

	public SDMoreView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		init();
	}

	private void init()
	{
		View view = LayoutInflater.from(getContext()).inflate(R.layout.view_more, null);
		mLlContent = (LinearLayout) view.findViewById(R.id.view_more_ll_content);
		mTvMore = (TextView) view.findViewById(R.id.view_more_tv_more);
		mTvMore.setOnClickListener(this);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		this.addView(view, params);
	}

	private void initViewState(boolean isShowAll)
	{
		if (mAdapter != null)
		{
			mTvMore.setText(mAdapter.getClickMoreString());

			if (mAdapter.getListCount() > mAdapter.getMaxShowCount())
			{
				mTvMore.setVisibility(View.VISIBLE);
			} else
			{
				mTvMore.setVisibility(View.GONE);
			}

			mLlContent.removeAllViews();
			for (int i = 0; i < mAdapter.getListCount(); i++)
			{
				if (isShowAll)
				{
					mLlContent.addView(mAdapter.getView(i));
				} else
				{
					if (i < mAdapter.getMaxShowCount())
					{
						mLlContent.addView(mAdapter.getView(i));
					}
				}
			}

		}
	}

	@Override
	public void onClick(View v)
	{
		if (v == mTvMore)
		{
			if (mAdapter != null)
			{
				if (mAdapter.clickMore(v))
				{
					// 事件被用户消费了
				} else
				{
					clickMore();
				}
			}
		}

	}

	private void clickMore()
	{
		if (mAdapter != null)
		{
			if (mLlContent.getChildCount() > mAdapter.getMaxShowCount())
			{
				initViewState(false);
				mTvMore.setText(mAdapter.getClickMoreString());
			} else
			{
				initViewState(true);
				mTvMore.setText(mAdapter.getClickBackString());
			}
		}
	}

}
